package com.sqx.modules.file;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.google.errorprone.annotations.Var;
import com.sqx.common.utils.Result;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.course.util.FfmpegUtil;
import com.sqx.modules.file.utils.FileUploadUtils;
import com.sqx.modules.file.utils.UploadMessageVo;
import com.sqx.modules.file.utils.UploadVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.sqx.modules.course.util.FfmpegUtil.addAWriteWatermark;

/**
 * 阿里云文件上传
 * @author fang
 * @date 2020/7/13
 */
@RestController
@Api(value = "阿里云文件上传", tags = {"阿里云文件上传"})
@RequestMapping(value = "/alioss")
@Slf4j
public class AliFileUploadController {


    private final CommonInfoService commonRepository;

    @Value(value = "${sqx.profile}")
    private String uploadPath;

    @Autowired
    public AliFileUploadController(CommonInfoService commonRepository) {
        this.commonRepository = commonRepository;
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ApiOperation("文件上传")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        String value = commonRepository.findOne(234).getValue();
        if("1".equals(value)){
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue());
            String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
            // 上传文件流。
            InputStream inputStream = null;
            try {
                inputStream =new ByteArrayInputStream(file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            String completePath=getPath(suffix);
            ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //        String src = commonRepository.findOne(72).getValue()+"/"+completePath;
            String src = commonRepository.findOne(19).getValue()+"/img/"+completePath;
            return Result.success().put("data",src);
        }else{
            try
            {
                String http = commonRepository.findOne(19).getValue();
                String[] split = http.split("://");
                // 上传文件路径
//                jiuzhou路径
//                String filePath ="/www/wwwroot/"+split[1]+"/file/uploadPath";
//                7wang路径
                String filePath ="/home/web/"+split[1]+"/file/uploadPath";
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = http +fileName;
                UploadVo uploadVo = new UploadVo();
                uploadVo.setFileUrl(url);
                uploadVo.setOriginalFilename(file.getOriginalFilename());
//                ==============================
                // 上传文件路径
//                String filePath = uploadPath;
//                String fileName = FileUploadUtils.upload(filePath, file);
//                System.out.println("===============>"+fileName);
//                String url1 = getUrl();
//                String url = url1 + fileName;
                return Result.success().put("data",url).put("originalFilename",file.getOriginalFilename());
            }
            catch (Exception e)
            {
                log.error("本地上传失败："+e.getMessage(),e);
                return Result.error(-100,"文件上传失败！");
            }
        }

    }

    @RequestMapping(value = "/uploadUniApp", method = RequestMethod.POST)
    @ApiOperation("文件上传")
    @ResponseBody
    public String uploadUniApp(@RequestParam("file") MultipartFile file){
        String value = commonRepository.findOne(234).getValue();
        if("1".equals(value)){
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue());
            String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
            // 上传文件流。
            InputStream inputStream = null;
            try {
                inputStream =new ByteArrayInputStream(file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            String completePath=getPath(suffix);
            ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            return commonRepository.findOne(19).getValue()+"/img/"+completePath;
        }else{
            try
            {
                String http = commonRepository.findOne(19).getValue();
                String[] split = http.split("://");
                // 上传文件路径
                String filePath ="/www/wwwroot/"+split[1]+"/file/uploadPath";
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = http +fileName;
                return url;
            }
            catch (Exception e)
            {
                log.error("本地上传失败："+e.getMessage(),e);
                return null;
            }
        }

    }



    @RequestMapping(value = "/batchUpload", method = RequestMethod.POST)
    @ApiOperation("文件批量上传")
    @ResponseBody
    public Result batchUpload(@RequestParam("files") List<MultipartFile> files){

        if (ObjectUtils.isNotEmpty(files))
        {
            ExecutorService executor = Executors.newFixedThreadPool(10);
            UploadMessageVo uploadMessageVo = new UploadMessageVo();
            List<UploadVo> uploadVos = new ArrayList<>();
            //获取失败文件的文件名
            ArrayList<String> arrayList = new ArrayList<>();
                for (MultipartFile file : files)
            {

                {
                    executor.submit(() -> {
                        //获取原始文件名
                        String originalFilename = file.getOriginalFilename();
                        System.out.println("===========>originalFilename:"+originalFilename);
                        UploadVo uploadVo = new UploadVo();
                        uploadVo.setOriginalFilename(originalFilename);
//                        ============================
//                        本地测试
//                        String filePath =uploadPath;
//                        System.out.println("===========>filePath:"+filePath);
//                        String http = "http://localhost:8182/sqx_fast";
//                        System.out.println("============>str:"+http);
//                        ==========================
//                        +++++++++++++++++++++++++++++++++++++++++
//                        线上环境
                        String http = commonRepository.findOne(19).getValue();
                        String[] split = http.split("://");
                        // 上传文件路径
                        String filePath ="/home/web/"+split[1]+"/file/uploadPath";
//                        ++++++++++++++++++++++++++++++
                        // 上传并返回新文件名称
                        String fileName = null;
                        try {
                            fileName = FileUploadUtils.upload(filePath, file);
                            System.out.println("===============>:fileName"+fileName);
                        } catch (IOException e) {
                            String name = file.getOriginalFilename();
                            arrayList.add(name);
                            log.error("文件上传失败："+e.getMessage(),e);
                            System.out.println("文件上传失败"+e.getMessage());
                        }
                        uploadVo.setFileToName(fileName);
                        //返回文件路径
                        String url = http +fileName;
                        uploadVo.setFileUrl(url);
                        uploadVos.add(uploadVo);
                    });

                }
            }
            executor.shutdown();
            try {
                executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            uploadMessageVo.setLoseList(arrayList);
            uploadMessageVo.setUploadVos(uploadVos);
            return Result.success().put("data",uploadMessageVo);
        }
        return Result.success();
    }

    /**
     * 上传文件时添加水印
     * @param file
     * @param text
     * @return
     */
    @PostMapping("/processUploadedFileWithWatermark")
    public Result processUploadedFileWithWatermark(MultipartFile file,String text) throws IOException {

        String http = getUrl();
        String filePath = uploadPath;
        // 上传文件路径
        String path = "D:\\ruoyi\\uploadPath"+"/file/uploadPath";
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(path, file);
        String str = fileName;
        // 生成临时输入文件路径
        Path tempInputPath = Files.createTempFile("input", null);
        System.out.println("++++++++++++++++++++++"+tempInputPath);
        //Paths.get("path", "to", "file.txt")将字符串"path"、"to"和"file.txt"转换为Path对象，表示文件路径"path/to/file.txt"。
        Path source = Paths.get(filePath + fileName);
        System.out.println("=================>source"+source);
        Files.copy(source, tempInputPath, StandardCopyOption.REPLACE_EXISTING);
        // 生成临时输出文件路径
//        Path tempOutputPath = Files.createTempFile("output", null);
        String tempOutputPath = "C:\\Users\\yang\\Desktop\\临时文件\\toPath\\aa\\str.mp4";
        // 添加水印
        addAWriteWatermark(filePath + fileName, text, tempOutputPath.toString());

        // 删除临时输入文件
        Files.delete(tempInputPath);
        //删除原始文件
        Files.delete(Paths.get(filePath + fileName));

        // 生成唯一的输出文件名
        // 生成最终输出文件路径
        Path finalOutputPath = Paths.get("C:\\Users\\yang\\Desktop\\临时文件\\toPath\\aa", "str.mp4");
        // 将临时输出文件移动到最终输出位置
        Files.move(Paths.get(tempOutputPath), Paths.get(filePath + fileName));

        //返回文件路径
        String url = http +str;
        return Result.success().put("data",url);
    }




    public String getUrl(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) attributes;
        HttpServletRequest request = requestAttributes.getRequest();
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).append("/").toString();
    }

    private String getPath(String suffix) {
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path =format(new Date()) + "/" + uuid;
        return path + suffix;
    }


    private String format(Date date) {
        if(date != null){
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
            return df.format(date);
        }
        return null;
    }


}
